package com.mingzhi.forum.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.dao.ArticleReplyMapper;
import com.mingzhi.forum.exception.ApplicationException;
import com.mingzhi.forum.model.ArticleReply;
import com.mingzhi.forum.service.IArticleReplyService;
import com.mingzhi.forum.service.IArticleService;
import com.mingzhi.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;

    /**
     * 帖子下面新增回复 实现
     *
     * @param articleReply 回复信息对象
     */
    @Override
    public void create(ArticleReply articleReply) {
        //进行非空校验
        if (articleReply == null
                || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造articleReply对象 设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        //写入数据库
        int i = articleReplyMapper.insertSelective(articleReply);
        if(i != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + ", 受影响行数不等于1.");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子表回复数
        articleService.addOneArticleReplyCountById(articleReply.getArticleId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //对参数进行非空校验
        if (articleId == null || articleId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用mapper层进行查询
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        return result;
    }
}
